/*
 * ValueEqualityPredicate.java
 *
 * Created on Jun 4, 2007, 11:39:28 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package com.infomancers.collections.predicates;

import com.infomancers.collections.*;
import java.lang.reflect.Method;

/**
 *
 * @author aviadbd
 */
public class ValueEqualityPredicate<T> implements Predicate<T> {
    
    private String isMethodName;
    private String getMethodName;
    private Object value;
    
    public ValueEqualityPredicate(String propertyName, Object value) {
        this.value = value;
        
        char[] nameChars = propertyName.toCharArray();
        nameChars[0] = Character.toUpperCase(nameChars[0]);
        isMethodName = "is" + nameChars;
        getMethodName = "get" + nameChars;
    }
    
    public boolean isTrue(T item) {
        for (Method m : item.getClass().getMethods()) {
            if (m.getName().equals(isMethodName) || m.getName().equals(getMethodName)) {
                try {
                    Object result = m.invoke(item);
                    
                    return value == null ? result == null : value.equals(result);
                } catch (Exception e) {
                    return false;
                }
                
            }
        }
        
        return false;
    }
}
